package com.leadingsoft.pwxk.utils;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;

import com.leadingsoft.pwxk.dto.FileInfoDto;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConnectUtil {
	private static String ENCODE = "utf-8";

	public static FileInfoDto sendRequest(String url) {
		FileInfoDto fileInfo = new FileInfoDto();
		try {
			if (null == url || "".equals(url)) {
				log.info("文件下载地址为空");
				return null;
			}
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			String[] split = conn.getHeaderField("Content-Disposition").split(";");
			String fileName = null;
			for (int i = 0; i < split.length; i++) {
				if (split[i].indexOf("filename=") != -1) {
					fileName = split[i].replace("filename=", "");
					break;
				}
			}

			String fn = getURLDecoderString(fileName);
			String path = FileUtil.saveFile(conn.getInputStream(), fn);
			fileInfo.setFilename(fn);
			fileInfo.setPath(path);
			return fileInfo;

		} catch (Exception e) {
			log.error("获取文件请求异常:" + e.getMessage(), e);
		}
		return null;
	}

	// 解码文件名
	public static String getURLDecoderString(String str) {
		if (null == str) {
			return null;
		}
		try {
			return java.net.URLDecoder.decode(str, ENCODE);
		} catch (UnsupportedEncodingException e) {
			log.error("文件名解码异常:" + e.getMessage(), e);
		}
		return null;
	}

}
